package com.hcc.flow.server.common.utils;


/**
 * @author zhengqiang
 * @description 根据ID生成推广标识工具
 */
public class ExtensionCodeUtil {
	
	/**
	 * 补全字符，用作位数不足时的补全
	 */
	private static final String completionFlag = "ol3g7h0nai";
	
	/**
	 * 自定义进制的进制位
	 */
	private static final String places = "e9pq1dty2fr5cxz8umsw46kvbj";

	/**
	 * @param number
	 * @return 将十进制转换为自定义进制
	 */
	private static String customHexadecimal(long number){
		int hexadecimal = places.length();
		String str = "";
		do{
			str = places.charAt((int)number % hexadecimal) + str;
			number /= hexadecimal;
		}while(number != 0);
		return str;
	}
	
	/**
	 * @param str
	 * @return 将自定义进制转换为十进制
	 */
	private static long changeCustomHexadecimalToNormal(String str){
		str = str.replaceAll("["+completionFlag+"]", "");
		int hexadecimal = places.length();
		long result = 0;
		for(int i = 0;i < str.length();i++){
			int index = places.indexOf(str.charAt(i));
			if(index < 0){
				throw new RuntimeException("错误的编码");
			}
			result += index * Math.pow(hexadecimal, str.length() - i - 1);
		}
		return result;
	}
	
	/**
	 * @param code
	 * @return 将唯一编码反解成ID值
	 */
	public static long extensionCodeToLong(String code){
		return changeCustomHexadecimalToNormal(code);
	}
	
	/**
	 * @param id
	 * @return 根据ID生成唯一编码
	 */
	public static String makeExtensionCode(long id){
		String str = customHexadecimal(id);
		char bit = str.charAt(0);
		int len = str.length();
		if(len < 6){
			for(int i = 0;i < 6 - len;i++){
				str += completionFlag.charAt((bit * i) % completionFlag.length());
			}
		}
		return str;
	}
	
}
